<?php
/*
	后台页面模版安装
*/
defined('BY_JYA') or exit('error');
$_RQ['op']=$_RQ['op']?$_RQ['op']:'installed';
$manage_op=array('uninstall','hide','show','bak','info','update');
if(in_array($_RQ['op'],$manage_op)){
	$id=intval($_RQ['id']);
	if(!$id){
		exi('请先选择模版！','error');
	}
	$plugin=pdo_get('core_manage_template',array('id'=>$id));
	if(!$plugin){
		exi('指定模版不存在！','error');
	}
}
$return=array();
$tabs=array(
	array('op'=>'installed','title'=>'模版列表'),
	array('op'=>'updates','title'=>'待更新模版'),
	array('op'=>'prepared','title'=>'待安装模版'),
	//array('op'=>'local','title'=>'本地模版'),
);

if($_RQ['op'] == 'installed'){
	
	$_AR['page']['title'] = '模版列表';
	$params=array();
	if(!empty($_RQ['title'])){
		$params['title like']='%'.trim($_RQ['title']).'%';
		$return['params']['title']=$_RQ['title'];
	}
	$orderby='id desc';
	$pindex = max(1, intval($_RQ['page']));
	$psize = 10;
	$total='';
	$fields=array();
	$list=pdo_getslice('core_manage_template',$params,array($pindex,$psize),$total,$fields,'',$orderby);
	
	$return['list']=$list;
	$totalpage=ceil($total/$psize);
	$totalpage=intval($totalpage);
	$return['totalpage'] =$totalpage;
	$return['params']['page'] =$pindex;
	$return['htmls']=array(
		'type'=>'list',
		'tabs'=>$tabs,
		'list'=>array('tip'=>'已安装模版列表','data'=>'list','del_one'=>false,'delall'=>false,'edit'=>false,'list'=>array(
			array('name'=>'title','title'=>'模版名称','type'=>'string'),
			array('name'=>'name','title'=>'模版标识','type'=>'string'),
			array('name'=>'version','title'=>'模版版本','type'=>'string'),
			//array('op'=>'info','title'=>'查看详情','type'=>'post'),
		),'action'=>array(
			//array('type'=>'href','op'=>'detail','title'=>'设置详情'),
			//array('type'=>'post','op'=>'hide','title'=>'隐藏','show'=>array('type >'=>1,'hide'=>0),'message'=>'隐藏后，该功能将无法使用，确定隐藏吗？'),
			//array('type'=>'post','op'=>'show','title'=>'显示','show'=>array('type >'=>1,'hide'=>1)),
			//array('type'=>'href','op'=>'bak','title'=>'回滚'),
			array('type'=>'post','op'=>'uninstall','title'=>'卸载','message'=>'卸载将删除该模版的文件和数据，且不可恢复！确认卸载吗！'),
		)),
		'search'=>array(
			array('type'=>'string','width'=>'30','name'=>'title','title'=>'模版名称'),
		),
	);
	exi($return);
}

if ($_RQ['op'] == 'bak'){
	$return=array('item'=>array('id'=>$plugin['id']));
	$return['htmls']=array(
		'type'=>'edit',
		'post'=>'bak_post',
		'desc'=>'本回滚功能用于回滚系统更新时自动进行的备份。自行修改的文件无法在此处回滚！',
		'tabs'=>array(
			array('op'=>'installed','title'=>'返回模版列表'),
		),
		'edit'=>array(
			array('type'=>'time','name'=>'time','title'=>'回滚时刻','help'=>'设置回滚到哪一时刻'),
		),
	);
	exi($return);
}
if ($_RQ['op'] == 'bak_post'){
	//回滚模版
	$post=get_postdata();
	$plugin=pdo_get('core_manage_template',array('id'=>intval($post['id'])));
	if(!$plugin){
		exi('指定模版不存在！','error');
	}
	$time=strtotime($post['time']);
	$baks=array();
	$mdir=ROOT_AT .'module_baks/'.$plugin['name'];
	//exi($mdir,'error');
	if(is_dir($mdir)){
		
		$bak = array();
		$bak_time=array();
		$baks=scandir($mdir);
		foreach($baks as $temp){
			if($temp=='.'||$temp=='..'){
				continue;
			} 
			$mtim=strrchr($temp,'.');
			$mtime=substr($mtim,1);
			if((int)$mtime > $time){
				$bak[$mtime]=$temp;
				$bak_time[]=$mtime;
			}
		}
		if($bak){
			arsort($bak_time,SORT_NUMERIC);
			if($plugin['type']==4){
				$plugin_dir=ROOT_D .'/addons/'.$plugin['name'];
			}else{
				$plugin_dir=ROOT_PLUGIN.$plugin['name'];
			}
			foreach($bak_time as $time){
				$zip = new ZipArchive();
				$zip->open($mdir.'/'.$bak[$time]);
				$zip->extractTo($plugin_dir);
				$zip->close();
				@unlink($mdir.'/'.$bak[$time]);
			}
			$bakr=strrchr($bak[$time],'.');
			$version=str_replace($bakr,'',$bak[$time]);
		}
	}
	$update=array('release'=>$time);
	if($version){
		$update['version']=$version;
	}
	pdo_update('core_manage_template',$update,array('id'=>$plugin['id']));
	exi('成功将模块回滚至指定时刻！','success','installed');
}
if ($_RQ['op'] == 'uninstall'){
	pdo_delete('core_manage_template',array('id'=>$plugin['id']));
	exi('卸载成功！');
}
if($_RQ['op'] == 'updates') { 
	//待更新组件列表，此处显示所有待更新的组件
	$params=array('is_my'=>0);
	if(!empty($_RQ['title'])){
		$params['title like']='%'.trim($_RQ['title']).'%';
		$return['params']['title']=$_RQ['title'];
	}
	$fields=array();
	$list=pdo_getall('core_manage_template',$params,$fields,'name');
	if($list){
		$names=array_keys($list);
		$post=array('names'=>$names);
		$versions=cloud_request('update.manage_template.getup',$post);
		foreach($versions as $name=>$version){
			if($version['release']<=$list[$name]['release']){
				//去掉无需更新的模版
				unset($list[$name]);
			}else{
				$list[$name]['new_version']=$version['version'];
			}
		}
	}
	$return['list']=$list;
	$htmls=array(
		'type'=>'list',
		'tabs'=>$tabs,
		'list'=>array('tip'=>'更新存在新版本的功能模版','data'=>'list','del_one'=>false,'delall'=>false,'edit'=>false,'pagelist'=>false,'list'=>array(
			array('name'=>'title','title'=>'模版名称','type'=>'string'),
			array('name'=>'version','title'=>'当前版本','type'=>'string'),
			array('name'=>'new_version','title'=>'最新版本','type'=>'string'),
			//array('op'=>'info','title'=>'更新说明','type'=>'post'),
		),'action'=>array(
			array('type'=>'href','op'=>'update','title'=>'更新'),
		)),
		'search'=>array(
			array('type'=>'string','width'=>'30','name'=>'title','title'=>'模版名称'),
		),
	);
	$return['htmls']=$htmls;
	exi($return);
}
if($_RQ['op'] == 'info'){
	//info功能后期完善
	$url='http://s.jinyunweb.com/manage/index.php?action=store.plugins&op=detail&id='.$plugin['cloud_id'];
	exi('','','',$url);
}
if($_RQ['op'] == 'update') {
	//更新模版
	$dir = ROOT_D.'/manage/templates/'. $plugin['name'];
	$update_data_file=ROOT_AT.'template_'.$plugin['name'].'.update';
	if(!$_SESSION['download'] || !is_file($update_data_file)){
		$post=array('name'=>$plugin['name']);
		
		
		$post['release']=$plugin['release'];
		$dat=cloud_request('update.manage_template.build',$post);
		//更新模版数据
		pdo_update('core_manage_template',$dat['update'],array('id'=>$plugin['id']));
		//更新文件
		$upfiles=$files = array();
		if(!empty($dat['files'])) {
			$mdir=ROOT_AT .'manage_template_baks/'.$plugin['name'];
			if(!is_dir($mdir)){
				cfc('files')->mkdirs($mdir);
			}
			$bak = $mdir.'/'.$plugin['version'].'.'.TIMESTAMP;
			$zip= new ZipArchive();
			$zip->open($bak, ZipArchive::CREATE);
			foreach($dat['files'] as $file) {
				$entry = $dir . $file['path'];
				if(!is_file($entry) || md5_file($entry) != $file['checksum']) {
					$files[] =$file['path'];
					$upfiles[]=$file;
				}
				if(is_file($entry) && md5_file($entry) != $file['checksum']) {
					$zip->addFile($entry,$file['path']);
				}
			}
			$zip->close();
		}
		//检查文件权限
		if(!empty($files)){
			$error=array();
			foreach($files as $f){
				$path = $dir.$f;
				if(file_exists($path)){
					if(!is_writable($path)){
					 $error[]=$path.'文件没有写入的权限';
					}
				}else{
					$path=get_dirname($path);
					if(!is_writable($path)){
					$error[]=$path.'文件夹没有写入的权限';
					}
				}
			}
			if($error){
				$error=implode(';',$error);
				exi($error,'error');
			}
		}
	
		if(!empty($files)){
			$post=array('name'=>$plugin['name'],'files'=>$files);
			$files=cloud_request('update.manage_template.getdata',$post);
			//下载更新文件时，如果内容较少，则一次性下载之，否则跳转下载页分批下载
			if($files['parts']==1){
				$data=cloud_request('update.download',array('id'=>$files['id'],'part'=>1),true);
				file_put_contents($update_data_file,$data);
			}else{
				$_SESSION['download']=array(
					'id'=>$files['id'],
					'parts'=>$files['parts'],
					'to'=>$update_data_file,
				);
				exi('准备下载更新文件！','success','core/cloud.download/');
			}
		}
	}
	if(is_file($update_data_file)){
		$zip = new ZipArchive();
		$zip->open($update_data_file);
		$zip->extractTo($dir);
		$zip->close();
		@unlink($update_data_file);
		
	}
	if($_SESSION['download']){
		unset($_SESSION['download']);
	}
	exi('更新成功！','','goback');
}
if($_RQ['op'] == 'prepared'){
	$_AR['page']['title'] = '待安装模版列表';
	$installed = pdo_getall('core_manage_template',array(),array('cloud_id'),'cloud_id');
	if($installed){
		$installed=array_keys($installed);
		$installed=implode(';',$installed);
	}
	$result=cloud_request('update.manage_template.getbuyed',array('installed'=>$installed));
	$return['list']=$result?:array();
	$htmls=array(
		'type'=>'list',
		'tabs'=>$tabs,
		'list'=>array('tip'=>'已购买但尚未安装的模版。如果这里没有您想要安装的模版，请先前往模版商城购买！','data'=>'list','key'=>'name','del_one'=>false,'delall'=>false,'edit'=>false,'pagelist'=>false,'list'=>array(
			array('name'=>'title','title'=>'模版名称','type'=>'string'),
			array('name'=>'version','title'=>'模版版本','type'=>'string'),
		),'action'=>array(
			array('type'=>'href','op'=>'install','title'=>'安装'),
		)),
	);
	$return['htmls']=$htmls;
	exi($return);
}
if($_RQ['op'] == 'install') {
	//安装模版
	
	$id=trim($_RQ['name']);
	if(!$id){
		exi('请先选择要安装的模版！','error','goback');
	}
	$template_dir=ROOT_D.'/manage/templates/'.$id;
	$install_data_file=ROOT_AT.'template_'.$id.'.install';
	if(!$_SESSION['download'] || !is_file($install_data_file)){
		if (pdo_getcolumn('core_manage_template',array('name'=>$id),'id')) {
			exi('模版已经安装或是唯一标识已存在！','error','goback');
		}
		if(is_file($install_data_file)){
			@unlink($install_data_file);
		}
		//获取模版基本数据
		$post=array('name'=>$id);
		$module=cloud_request('update.manage_template.install',$post);
		
		//获取模版安装文件
		if(!is_dir($template_dir)){
			//本地没有文件，直接下载
			$download=$module['files'];
		}else{
			//对比更新
			$res=cloud_request('update.manage_template.build',array('name'=>$id,'only_file'=>true));
			$upfiles=array();
			foreach($res['files'] as $row){
				$file=$template_dir.$row['path'];
				if(!is_file($file) || md5_file($file)!=$row['checksum']){
					$upfiles[]=$row['path'];
				}
			}
			if(!empty($upfiles)){
				//获取差异文件
				$post=array('name'=>$id,'files'=>$upfiles);
				$download=cloud_request('update.manage_template.getdata',$post);
			}else{
				//无需下载文件
				$download=array();
			}
		}
		if($download['parts']==1){
			$install_data=cloud_request('update.download',array('id'=>$download['id'],'part'=>1),true);
			file_put_contents($install_data_file,$install_data);
		}elseif($download['parts'] > 1){
			//将模版数据保存到临时文件中，开始下载文件
			$config=serialize($module);
			file_put_contents(ROOT_AT.'template_'.$id.'.config',$config);
			$_SESSION['download']=array(
				'id'=>$download['id'],
				'parts'=>$download['parts'],
				'to'=>$install_data_file,
			);
			exi('准备下载安装文件！','','core/cloud.download/');
		}
		//parts==0表示无需额外下载数据
	}
	if(!$module){
		$module=file_get_contents(ROOT_AT.'template_'.$id.'.config');
		$module=unserialize($module);
		@unlink(ROOT_AT.'template_'.$id.'.config');
	}
	if(is_file($install_data_file)){
		
		$zip = new ZipArchive();
		$zip->open($install_data_file);
		$zip->extractTo($template_dir);
		$zip->close();
		@unlink($install_data_file);
	}
	if($_SESSION['download']){
		unset($_SESSION['download']);
	}
	$indata=array(
		'cloud_id'=>$module['install']['id'],
		'name'=>$module['install']['name'],
		'title'=>$module['install']['title'],
		'version'=>$module['install']['version'],
		'release'=>$module['install']['release'],
		'diy_form'=>$module['install']['diy_form'],
		'createtime'=>time(),
	);
	pdo_insert('core_manage_template',$indata);
	exi('安装成功！','','goback');
}
/*
if($_RQ['op'] == 'local'){
	//本地模版安装和更新，含有config.json配置文件的模版即认为是本地模版
	if(!function_exists('scandir')){
		exi('检查本地模版需要用到“scandir”函数，请联系服务器管理员开启支持！','error');
	}
	$plugin_dirs=scandir(ROOT_PLUGIN);
	$local_plugins=array();
	foreach($plugin_dirs as $plugin_name){
		if($plugin_name=='.' || $plugin_name=='..'){
			continue;
		}
		$config_file=ROOT_PLUGIN.$plugin_name.'/config.json';
		//exi($config_file,'error');
		if(is_file($config_file)){
			$config_json=file_get_contents($config_file);
			$config_data=json_decode($config_json,true);
			
			if($config_data && $config_data['name'] && $config_data['title']){
				$local_plugins[]=array_fields(array('name','title','author','version','release','logo'),$config_data);
				
			}
		}
	}
	
	foreach($local_plugins as $key=>&$plugin){
		$plugin['logo']=$plugin['logo']?ROOT_PLUGIN.$plugin_name.$plugin['logo']:SITEROOT.'core/resource/images/gw-plus.png';
		$log=pdo_get('core_manage_template',array('name'=>$plugin['name']),array('id','release','version','cloud_id'));
		if(!$log){
			$plugin['is_new']=true;
		}else{
			if($log['cloud_id']){
				//对接了云平台
				unset($local_plugins[$key]);
				continue;
			}
			$plugin['installed']=true;
			if($plugin['release']>$log['release']){
				$plugin['update']=true;
				$plugin['new_version']=$plugin['version'];
				$plugin['version']=$log['version'];
			}
		}
	}
	//print_r($local_plugins);exit;
	$return['list']=$local_plugins;
	$return['htmls']=array(
		'type'=>'list',
		'tabs'=>$tabs,
		'list'=>array('data'=>'list','key'=>'name','tip'=>'本地模版列表','del_one'=>false,'delall'=>false,'edit'=>false,'list'=>array(
			array('name'=>'logo','title'=>'模版logo','type'=>'image'),
			array('name'=>'title','title'=>'模版名称','type'=>'string'),
			array('name'=>'name','title'=>'模版标识','type'=>'string'),
			array('name'=>'version','title'=>'模版版本','type'=>'string'),
			array('name'=>'new_version','title'=>'待更新版本','type'=>'string'),
		),'action'=>array(
			array('type'=>'post','op'=>'local_install','title'=>'安装','show'=>array('is_new'=>true)),
			array('type'=>'post','op'=>'local_update','title'=>'更新','show'=>array('update'=>true)),
			array('type'=>'post','op'=>'local_uninstall','title'=>'卸载','show'=>array('installed'=>true),'message'=>'确认卸载吗！'),
		)),
	);
	exi($return);
}
$local_ops=array('local_install','local_update','local_uninstall');
if(in_array($_RQ['op'],$local_ops)){
	$name=trim($_RQ['name']);
	if(!$name){
		exi('请先选择要安装的模版！','error');
	}
	if(preg_match('/\W/',$name)){
		exi('模版标识不合法！','error');
	}
	$config_file=ROOT_PLUGIN.$name.'/config.json';
	if(!is_file($config_file)){
		exi('模版配置文件不存在！','error');
	}
	
	$config_json=file_get_contents($config_file);
	$config_data=json_decode($config_json,true);
}
if($_RQ['op'] == 'local_install'){
	//本地安装
	$check=pdo_get('core_manage_template',array('name'=>$config_data['name']),'id');
	if($check){
		exi('模版已安装，请勿重复安装！','error');
	}
	if($config_data['install']){
		//安装数据表时，替换表前缀
		if(substr($config_data['install'],0,5)=='file:'){
			$install_file=ROOT_PLUGIN.$name.substr($config_data['install'],5);
			if(is_file($install_file)){
				$config_data['install']=file_get_contents($install_file);
			}
		}
		$sqls=str_replace('{table_pre}',TABLE_PRE,$config_data['install']);
		pdo_query($sqls);
	}
	$plugin=array(
		'name'=>$config_data['name'],
		'title'=>$config_data['title'],
		'version'=>$config_data['version'],
		'release'=>$config_data['release'],
		'description'=>$config_data['description'],
		'covers'=>$config_data['covers'],
		'menus'=>$config_data['menus'],
		'diypage'=>$config_data['diypage'],
		'basic'=>$config_data['basic'],
		'istakeover'=>intval($config_data['istakeover']),
		'style'=>intval($config_data['style']),
	);
	pdo_insert('core_manage_template',$plugin);
	
	if($config_data['permissions']){
		foreach($config_data['permissions'] as $perm){
			$new_perm=array_fields(array('type','title','action','op'),$perm);
			$new_perm['plugin']=$config_data['name'];
			pdo_insert('core_plugin_permissions',$new_perm);
		}
	}else{
		//插入基础权限集
		$permission=array(
			'type'=>1,
			'plugin'=>$plugin['name'],
			'title'=>$plugin['title'],
		);
		pdo_insert('core_plugin_permissions',$permission);
	}
	exi('安装成功！如果模块尚未出现在扩展功能栏，请刷新页面！','','local');
}
if($_RQ['op'] == 'local_update'){
	//本地更新
	
	$plugin=pdo_get('core_manage_template',array('name'=>$config_data['name']),array('id','version','release'));
	if(!$plugin){
		exi('模版尚未安装，无法更新！','error');
	}
	if($plugin['release']>=$config_data['release']){
		exi('模版已是最新，无需更新！','error');
	}
	
	if($config_data['versions']){
		foreach($config_data['versions'] as $version){
			if($version['release']>$plugin['release']){
				if($version['update']){
					if(substr($version['update'],0,5)=='file:'){
						$sql_file=ROOT_PLUGIN.$name.substr($version['update'],5);
						if(is_file($sql_file)){
							$version['update']=file_get_contents($sql_file);
						}
					}
					$sqls=str_replace('{table_pre}',TABLE_PRE,$version['update']);
					pdo_query($sqls);
				}
				$update=array(
					'version'=>$version['version'],
					'release'=>$version['release'],
				);
				pdo_update('core_manage_template',$update,array('id'=>$plugin['id']));
			}
		}
	}
	if($config_data['permission']){
		foreach($config_data['permission'] as $perm){
			$check=pdo_getcolumn('core_plugin_permissions',array('plugin'=>$config_data['name'],'action'=>$perm['action'],'op'=>$perm['op']),'id');
			if($check){
				pdo_update('core_plugin_permissions',array('type'=>$perm['type'],'title'=>$perm['title']),array('id'=>$check));
			}else{
				$new_perm=array_fields(array('type','title','action','op'),$perm);
				$new_perm['plugin']=$config_data['name'];
				pdo_insert('core_plugin_permissions',$new_perm);
			}
		}
	}
	$update=array_fields(array('description','covers','menus','diypage','basic','istakeover','title','type','style'),$config_data);
	pdo_update('core_manage_template',$update,array('id'=>$plugin['id']));
	exi('更新成功！','','local');
}
if($_RQ['op'] == 'local_uninstall'){
	//本地卸载：删除模版表记录、删除权限表记录、删除模版数据表
	$plugin=pdo_get('core_manage_template',array('name'=>$config_data['name']),array('id','name','title'));
	if(!$plugin){
		exi('模版尚未安装，无法卸载！','error');
	}
	if($config_data['uninstall']){
		if(substr($config_data['uninstall'],0,5)=='file:'){
			$uninstall_file=ROOT_PLUGIN.$name.substr($config_data['uninstall'],5);
			if(is_file($uninstall_file)){
				$config_data['uninstall']=file_get_contents($uninstall_file);
			}
		}
		$sqls=str_replace('{table_pre}',TABLE_PRE,$config_data['uninstall']);
		pdo_query($sqls);
	}
	pdo_delete('core_manage_template',array('id'=>$plugin['id']));
	pdo_delete('core_plugin_permissions',array('plugin'=>$plugin['name']));
	exi("模版【{$plugin['title']}】卸载成功",'','local');
}
*/
function get_dirname($file){
	$dir=dirname($file);
	if(!is_dir($dir)){
		$dir=get_dirname($dir);
	}
	return $dir;
}